package com.iman.common.video;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;

public class QNAuth {
 
	public Auth getAuth(QnKey key){
		Auth auth = Auth.create(key.a_key   , key.s_key);
		return auth;
	}
	
	public String getVideoURL(String baseUrl,long  expires ){
		Auth auth = getAuth( new QnKey() );
		String url = auth.privateDownloadUrl(baseUrl, expires);
		return url ;
	}
	
	public String getToken(String DownloadUrl ,QnKey key){
		byte[] singb = null;
		try {
			singb = getHmacSHA1(DownloadUrl, key.s_key);
		} catch ( Exception e) {
			e.printStackTrace();
			return  null;
		}
		String Sign = new String(singb);
		String EncodedSign = UrlSafeBase64.encodeToString (Sign);
		return key.a_key+":"+EncodedSign;
	}
	 
	
	private static byte[] getHmacSHA1(String src ,String key) throws NoSuchAlgorithmException, UnsupportedEncodingException,InvalidKeyException {  
	    Mac mac = Mac.getInstance("HmacSHA1");  
	    SecretKeySpec secret = new SecretKeySpec( key.getBytes() , mac.getAlgorithm());  
	    mac.init(secret);  
	    return mac.doFinal(src.getBytes());  
	}  
	
	
}
